package proxy

import (
	"fmt"
	"net/http"
	"strings"

	"git.oschina.net/index.php/gostudy/restful/helper"
	"github.com/ant0ine/go-json-rest/rest"
)

func (s *Service) GetAll(w rest.ResponseWriter, r *rest.Request) {
	s.RLock()
	users := make([]Proxy, len(s.Store))
	i := 0
	for _, service := range s.Store {
		users[i] = *service
		i++
	}
	s.RUnlock()
	w.WriteJson(&users)
}

func (s *Service) Show(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	s.RLock()
	var service *Proxy
	if s.Store[id] != nil {
		service = &Proxy{}
		*service = *s.Store[id]
	}
	s.RUnlock()
	if service == nil {
		// rest.NotFound(w, r)
		w.WriteJson(helper.Rerror("Service " + id + " not found."))
		return
	}
	w.WriteJson(service)
}

func (s *Service) Create(w rest.ResponseWriter, r *rest.Request) {
	service := Proxy{}
	err := r.DecodeJsonPayload(&service)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	s.Lock()
	ip := strings.Join(strings.Split(service.Ip, "."), "-")
	id := fmt.Sprintf("%s:%d", ip, service.Port) // stupid
	s.Store[id] = &service
	s.Unlock()

	service.AddVip(s.Iface)
	//	go service.AddLvs()
	service.AddRule()

	w.WriteJson(&service)
}

func (s *Service) Update(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	s.Lock()
	if s.Store[id] == nil {
		rest.NotFound(w, r)
		s.Unlock()
		return
	}
	service := Proxy{}
	err := r.DecodeJsonPayload(&service)
	if err != nil {
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		s.Unlock()
		return
	}
	s.Store[id] = &service
	s.Unlock()
	w.WriteJson(&service)
}

func (s *Service) Delete(w rest.ResponseWriter, r *rest.Request) {
	id := r.PathParam("id")
	s.Lock()
	if s.Store[id] == nil {
		rest.NotFound(w, r)
		s.Unlock()
		return
	}
	s.Store[id].DelLvs()
	delete(s.Store, id)
	s.Unlock()
	w.WriteHeader(http.StatusOK)

}

func (s *Service) ReloadAll(w rest.ResponseWriter, r *rest.Request) {
	//	r.ParseForm()
	//	svc := r.FormValue("svc")
	w.WriteJson(helper.Rsuccess("reload all success."))
	s.LoadConfig("")
}

func (s *Service) Reload(w rest.ResponseWriter, r *rest.Request) {
	id := helper.GetId(helper.GetIp(r))
	w.WriteJson(helper.Rsuccess("reload " + id + " success."))
	s.LoadConfig(id)
}
